import dayjs from "dayjs";
import editForm from "../Table.vue";
import { message } from "@/utils/message";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import { addDialog } from "@/components/ReDialog";
import {
  attachmentList,
  deleteAttachment,
  batchDeleteAttachment,
  attachmentTypes,
  attachmentCategory,
  updateAttachmentType
} from "@/api/general";

import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "./types";
import { getFilter } from "@/utils/filter";

export function useRole(tableRef: Ref) {
  const form = reactive({
    category: "",
    mimetype: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const categorys = ref([]);
  const mimetypes = ref([]);

  const imagetype = ["jpg", "png", "jpeg", "gif"];
  const videotype = ["mp4", "webm", "ogg"]; // 视频类型数组
  const audiotype = ["mp3", "wav", "ogg"]; // 音频类型数组
  // 压缩包
  const ziptype = ["zip", "rar", "7z", "tar", "gz"];
  // 文档类型
  const pdftype = ["pdf"];

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "序号",
      prop: "id",
      minWidth: 90
    },
    {
      label: "类型",
      prop: "category",
      minWidth: 100
    },
    {
      label: "预览",
      prop: "url",
      width: 100,
      cellRenderer: ({ row }) => {
        // 如果再imagetype数组中，则显示图片，否则显示类型
        // 如果时视频文件，显示视频图标
        // 其他文件显示文件图标
        const type = row.imagetype.toLowerCase();
        let img_type = "file";
        // 判断文件类型，生成不同的DOM
        if (imagetype.includes(type)) {
          // 如果是图片类型
          return (
            <a target="_blank" href={row.url}>
              <el-image
                preview-teleported
                loading="lazy"
                src={row.url}
                initial-index={row.id}
                fit="cover"
                class="w-[100px] h-[100px]"
              />
            </a>
          );
        } else if (videotype.includes(type)) {
          img_type = "video";
        } else if (audiotype.includes(type)) {
          img_type = "audio";
        } else if (ziptype.includes(type)) {
          img_type = "zip";
        } else if (pdftype.includes(type)) {
          img_type = "pdf";
        }
        console.log(img_type);
        const src = "/src/assets/utils/attachment_" + img_type + "_icon.svg";
        console.log(src);
        return (
          <a target="_blank" href={row.url}>
            <el-image
              preview-teleported
              loading="lazy"
              src={src}
              initial-index={row.id}
              fit="cover"
              class="w-[100px] h-[100px]"
            />
          </a>
        );
      }
    },
    {
      label: "文件大小(kb)",
      prop: "filesize",
      minWidth: 100
    },
    {
      label: "宽度(px)",
      prop: "imagewidth",
      minWidth: 100
    },
    {
      label: "高度(px)",
      prop: "imageheight",
      minWidth: 100
    },
    {
      label: "类型",
      prop: "imagetype",
      minWidth: 100
    },
    {
      label: "存储引擎",
      prop: "storage",
      minWidth: 100
    },
    {
      label: "更新时间",
      prop: "updatetime",
      minWidth: 180,
      formatter: ({ updatetime }) =>
        dayjs(updatetime * 1000).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "创建时间",
      prop: "createtime",
      minWidth: 180,
      formatter: ({ createtime }) =>
        dayjs(createtime * 1000).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function openDialog(title = "新增", row?: FormItemProps) {
    console.log(row);
    addDialog({
      title: `${title}附件`,
      props: {
        formInline: {
          id: row?.id ?? 0,
          category: row?.category ?? "",
          fileList: row?.fileList ?? [],
          url: row?.url ?? "",
          imagetype: row?.imagetype ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          done();
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            if (title !== "新增") {
              updateAttachmentType({
                id: curData.id,
                category: curData.category
              }).then(res => {
                if (res.code) {
                  message(`文件类型修改成功`, {
                    type: "success"
                  });
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            } else {
              chores();
            }
          }
        });
      }
    });
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = parseInt(val as any);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    batchDeleteAttachment(getKeyList(curSelected, "id")).then(res => {
      if (res.code) {
        message(`已删除序号为 ${getKeyList(curSelected, "id")} 的数据`, {
          type: "success"
        });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
      } else {
        message(res.msg, { type: "error" });
      }
    });
  }

  function handleDelete(row) {
    deleteAttachment({ id: row.id }).then(res => {
      if (res.code) {
        message("删除成功", { type: "success" });
        onSearch();
      } else {
        message(res.msg, { type: "error" });
      }
    });
  }
  async function onSearch() {
    loading.value = true;

    let filter = await getFilter(form);

    let ListRequest = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      filter,
      order: "desc"
    };

    const { data } = await attachmentList(ListRequest);
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
    attachmentCategory().then(res => {
      categorys.value = [];
      categorys.value.unshift("默认分类");
      categorys.value = categorys.value.concat(res.data);
    });
    // 获取附件类型
    // mimetype
    attachmentTypes().then(res => {
      mimetypes.value = [];
      mimetypes.value = mimetypes.value.concat(res.data);
    });
  });

  return {
    form,
    loading,
    columns,
    dataList,
    mimetypes,
    imagetype,
    categorys,
    pagination,
    selectedNum,
    onSearch,
    openDialog,
    resetForm,
    onbatchDel,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
